package com.etoak.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.config.KaptchaConfig;
import com.etoak.dto.LoginDTO;
import com.etoak.service.UserService;
import com.etoak.vo.CodeVO;
import com.etoak.vo.TokenVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.etoak.common.constant.CommonConstant.REDSI_CODE_PREFIX;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    KaptchaConfig kaptchaConfig;

    @GetMapping("/code")
    public ResultVO<CodeVO> getCode(){
        DefaultKaptcha kaptcha = kaptchaConfig.getDefaultKaptcha();
        // 1 需要通过kaptchaConfig 生成验证码code
        String codeText = kaptcha.createText();
        // 2 需要将验证码存储到redis中+3min的过期时间   key  value
        String uuid = IdUtil.simpleUUID();
        String key = REDSI_CODE_PREFIX + uuid;
        stringRedisTemplate.opsForValue().set(key,codeText,3, TimeUnit.MINUTES);
        // 3 根据code生成验证码图片BufferedImage
        BufferedImage image = kaptcha.createImage(codeText);
        // BufferedImage
        // ByteArrayOutputStream中
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // ImageIO.write
        try {
            ImageIO.write(image,"png",outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // => ByteArray
        // 4 生成base64编码
        // hutool Base64Encoder ByteArray
        String base64 = Base64Encoder.encode(outputStream.toByteArray());
        // 5 组装CodeVO
        String text = "data:image/png;base64,"+base64;
        CodeVO vo = new CodeVO(uuid,text);
        // 6 返回
        return ResultVO.success(vo);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResultVO<TokenVO> login(@Validated LoginDTO longinDTO){
        TokenVO tokenVO = userService.login(longinDTO);
        return ResultVO.success(tokenVO);
    }
}
